// pages/selectDrugs/selectDrugs.js
import Toast from '@vant/weapp/toast/toast';
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectDrugs: [],
    selectedIds: [],
    resultDrugs: []
  },
  async getSelectDrugs() {
    // 获取药品列表
    const res = await app.call({
      path: '/drug/getSelectDrugs',
      method: 'GET'
    })

    console.log(res)
    if (res.code === 0) {
      console.log(res.data)
      this.setData({
        selectDrugs: res.data.selectDrugs
      })
    } else {
      Toast.fail(res.errorMsg);
    }
    this.setData({
      showEmpty: this.data.selectDrugs.length === 0
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getSelectDrugs()
  },

  onChange(event) {
    this.setData({
      selectedIds: event.detail
    })
    const resultDrugs = this.data.selectedIds.map(id => {
      const drug = this.data.selectDrugs.find(item => item.id == id);
      return drug;
    });
    this.setData({
      resultDrugs: resultDrugs
    });
    console.log(this.data.resultDrugs)
  },

  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},

  onConfirm() {
    app.globalData.selectDrugs = this.data.resultDrugs
    console.log(app.globalData.selectDrugs)
    wx.navigateBack({
      delta: 1
    });
  }
})